package com.ruyuan.payment.server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.payment.common.models.AlipayTradeFastpayRefundQueryResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruyuan.payment.server.alipay.AliPayService;
import com.ruyuan.payment.server.domain.OrderPay;
import com.ruyuan.payment.server.domain.OrderPayRefund;
import com.ruyuan.payment.server.domain.OrderPayRefundExample;
import com.ruyuan.payment.server.enums.OrderPayChannelEnum;
import com.ruyuan.payment.server.enums.OrderPayRefundStatusEnum;
import com.ruyuan.payment.server.mapper.OrderPayRefundMapper;
import com.ruyuan.payment.server.req.OrderPayRefundQueryReq;
import com.ruyuan.payment.server.resp.OrderPayRefundQueryResp;
import com.ruyuan.payment.server.resp.PageResp;
import com.ruyuan.payment.server.util.CopyUtil;
import com.ruyuan.payment.server.wxpay.WxPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class OrderPayRefundService {

    private static final Logger LOG = LoggerFactory.getLogger(OrderPayRefundService.class);

    @Resource
    private OrderPayRefundMapper orderPayRefundMapper;

    @Resource
    private AliPayService aliPayService;

    @Resource
    private WxPayService wxPayService;

    @Resource
    private PayRefundService payRefundService;

    @Resource
    private OrderPayService orderPayService;

    public PageResp<OrderPayRefundQueryResp> queryList(OrderPayRefundQueryReq req) {
        Long memberId = req.getMemberId();
        OrderPayRefundExample orderPayRefundExample = new OrderPayRefundExample();
        OrderPayRefundExample.Criteria criteria = orderPayRefundExample.createCriteria();
        if (!ObjectUtils.isEmpty(memberId)) {
            criteria.andMemberIdEqualTo(memberId);
        }
        orderPayRefundExample.setOrderByClause("id desc");

        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<OrderPayRefund> orderPayRefundList = orderPayRefundMapper.selectByExample(orderPayRefundExample);

        PageInfo<OrderPayRefund> pageInfo = new PageInfo<>(orderPayRefundList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<OrderPayRefundQueryResp> queryRespList = CopyUtil.copyList(orderPayRefundList, OrderPayRefundQueryResp.class);

        PageResp<OrderPayRefundQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(queryRespList);

        return pageResp;
    }

    public String queryChannel(String refundNo) {
        OrderPayRefund orderPayRefundDB = selectByRefundNo(refundNo);
        OrderPay orderPayDB = orderPayService.selectByPayNo(orderPayRefundDB.getPayNo());
        if (ObjectUtils.isEmpty(orderPayRefundDB)) {
            LOG.warn("交易记录不存在，refundNo：{}", refundNo);
            return "交易记录不存在";
        }
        if (!OrderPayRefundStatusEnum.INIT.getCode().equals(orderPayRefundDB.getStatus())) {
            LOG.warn("支付状态非【未支付】，refundNo：{}，status：{}", refundNo, orderPayRefundDB.getStatus());
            return "支付状态非【未支付】";
        }

        if (OrderPayChannelEnum.ALIPAY.getCode().equals(orderPayRefundDB.getChannel())) {
            AlipayTradeFastpayRefundQueryResponse response = aliPayService.queryRefund(orderPayRefundDB.getPayNo(), refundNo);
            String tradeStatus = response.getRefundStatus();
            if ("REFUND_SUCCESS".equals(tradeStatus)) {
                payRefundService.refund(orderPayDB, orderPayRefundDB);
                return "查询支付通道退款成功！";
            } else {
                return "通道返回：" + response.getSubMsg();
            }
        } else if (OrderPayChannelEnum.WXPAY.getCode().equals(orderPayRefundDB.getChannel())) {
            String bodyStr = wxPayService.queryRefund(refundNo);
            JSONObject responseJson = JSON.parseObject(bodyStr);
            String status = responseJson.getString("status");
            if ("SUCCESS".equals(status)) {
                Date date = responseJson.getDate("success_time");
                payRefundService.refund(orderPayDB, orderPayRefundDB);
                return "查询支付通道交易成功！";
            } else {
                return "";
            }
        }

        return "";
    }

    public OrderPayRefund selectByRefundNo(String refundNo) {
        OrderPayRefundExample orderPayRefundExample = new OrderPayRefundExample();
        orderPayRefundExample.createCriteria().andRefundNoEqualTo(refundNo);
        List<OrderPayRefund> list = orderPayRefundMapper.selectByExample(orderPayRefundExample);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
    }

}
